const router = require("koa-router")()
const render = require("../config")
const main = require("../models")
router.get("/login",async ctx=>{
    await ctx.render("login")
})
router.get("/register",async ctx=>{
    await ctx.render("register")
})
router.get("/home",async ctx=>{
    ctx.body = '首页'
})
router.post("/doRegister",async ctx=>{
    var {username,password} = ctx.request.body
    var collection = await main("user")
    var res = await collection.find({username}).toArray()
    if(res.length){
        ctx.body = "<script>alert('用户名已经存在');location.href='./register'</script>"
    }else{
        await collection.insertOne({username,password})
        ctx.body = "<script>alert('注册成功');location.href='/home'</script>"
    }
})
router.post("/doLogin",async ctx=>{
    var {username,password} = ctx.request.body
    var collection = await main("user")
    var res = await collection.find({username,password}).toArray()
    if(res.length){
        ctx.redirect("/home")
    }else{
        ctx.body = "<script>alert('用户名或密码错误');location.href='./login'</script>"
    }
})

module.exports = router